<?php
/**
 * Created by Sublime.
 * Author: lingyun
 * Date: 2017-12-07 15:29:32
 * @desc 支付回调业务处理
 */
namespace app\index\controller;
use think\Controller;
use think\Db;
use alipay\Query;
use alipay\Notify as Alinotify;
use app\index\service\WeixinService;
use think\Config;
class Notify extends Controller{

    /**
     * @Author  lingyun
     * @Desc    微信支付订单
     * 2018-06-15
     */
    public function notifyweixinpay(){
        $pay = & load_wechat('Pay');
        // 获取支付通知
        $notifyInfo = $pay->getNotify();
//        file_put_contents('log.txt',$notifyInfo);
        // 支付通知数据获取失败
        if($notifyInfo===FALSE){
            // 接口失败的处理
            $this->error('支付失败',url('User/index'),1);
            //echo $pay->errMsg;
            //$json = json_encode($notifyInfo);
        }else{
            if ($notifyInfo['result_code'] == 'SUCCESS' && $notifyInfo['return_code'] == 'SUCCESS') {
                //订单详情
                $order = Db::name('order')->where("order_sn",$notifyInfo['out_trade_no'])->find();
                //会员信息
                $member = Db::name('user')->where('uid',$order['uid'])->field('uid,openid,addtime')->find();
                //更新订单状态,进行判断防止多次进行数据库操作
                if($order['pay_status'] == 0){
                    //更新订单信息
                    Db::name('order')->where('order_sn',$notifyInfo['out_trade_no'])->update(array('pay_code'=>$notifyInfo['transaction_id'],'pay_status'=>1,'pay_time'=>time(),'remark'=>'已支付','order_status'=>1));
                    //支付记录
//                    Db::name('pay_log')->insert(['order_id'=>$order['id'],'order_sn'=>$notifyInfo['out_trade_no'],'order_type'=>1,'uid'=>$order['uid'],'pay_type'=>2,'pay_sign'=>1,'amount'=>$order['final_amount'],'addtime'=>time(),'remark'=>'支付订单']);
                    //订单动作
                    Db::name('order_action')->insert(['uid'=>$order['uid'],'order_id'=>$order['id'],'action_user'=>0,'order_status'=>1,'pay_status'=>1,'status_desc'=>'已支付，待发货','storeid'=>$order['store_id'],'addtime'=>time()]);

                    //订单详情
                    $order_detail = db('order_details')->where('order_id',$order['id'])->field('id,uid,goods_num,order_id,spec_id,spec_detail,store_goods_stock_id')->select();

                    $ids = implode(',',array_column($order_detail, 'id'));
//                    $store_goods_stock_id = implode(',',array_column($order_detail, 'store_goods_stock_id'));

                    //更新订单详情的支付状态
                    db('order_details')->where('id','in',$ids)->update(['status'=>1]);
                    foreach($order_detail as $k => $v){
                        $stock = db('store_goods_stock')->where('id',$v['store_goods_stock_id'])->find();
                        $cur_stock = $stock['stock'] - $v['goods_num'];
                        //更新门店库存
                        db('store_goods_stock')->where('id',$v['store_goods_stock_id'])->update(['stock'=>$cur_stock]);
                        $arr = [
                            'goods_id'=>$v['goods_id'],
                            'goods_spec_id'=>$stock['goods_spec_id'],
                            'title'=>$v['spec_detail'],
                            'order_id'=>$order['id'],
                            'store_id'=>$order['store_id'],
                            'types'=>2,
                            'ruku_num'=>0,
                            'tuihuo_num'=>0,
                            'chuku_num'=>$v['goods_num'],
                            'sunhao_num'=>0,
                            'remark'=>'售卖'.$v['goods_num'],
                            'cur_stock'=>$cur_stock,
                            'addtime'=>time(),
                            'order_sn'=>$order['order_sn'],
                        ];
                        db('store_goods_log')->insert($arr);
                    }

                    //更新优惠券的使用情况
                    db('user_ycard')->where(['uid'=>$order['uid'],'id'=>$order['coupon_id']])->update(['order_id'=>$order['id'],'used_time'=>time(),'is_used'=>1]);
                    //更新代金券的使用情况
                    db('user_ycard')->where(['uid'=>$order['uid'],'id'=>$order['cash_coupon_id']])->update(['order_id'=>$order['id'],'used_time'=>time(),'is_used'=>1]);

                    $pay_log_arr = [
                        'order_id'=>$order['id'],
                        'order_sn'=>$order['order_sn'],
                        'order_type'=>1,
                        'uid'=>$order['uid'],
                        'pay_type'=>$order['pay_type'],
                        'pay_sign'=>1,
                        'store_id'=>$order['store_id'],
                        'amount'=>$order['final_amount'],
                        'remark'=>'线上购买商品，订单号'.$order['order_sn'].'，总价：'.$order['final_amount'],
                        'addtime'=>time(),
                        'store_id'=>$order['store_id']
                    ];
                    db('pay_log')->insert($pay_log_arr);            //新增支付记录

                    $store = db('store')->where('id',$order['store_id'])->find();           //查询门店信息
                    $update_store_credit_data = [
                        'total_amount'=>$store['total_amount']+$order['final_amount'],
                        'wx_money'=>$store['wx_money']+$order['final_amount']
                    ];
                    //增加门店线上微信收入
                    db('store')->where('id',$order['store_id'])->update($update_store_credit_data);

                    $store_credit_log = [
                        'store_id' => $order['store_id'],
                        'order_id' => $order['id'],
                        'type' => 1,
                        'credit' => $order['final_amount'],
                        'cur_credit' => $store['total_amount'] + $order['final_amount'],
                        'remark' => '销售商品收入',
                        'addtime' => time(),
                        'order_type' => 1,
                        'order_sn' => $order['order_sn'],
                        'pay_type' => 2
                    ];

                    db('store_credit_log')->insert($store_credit_log);


                    //三级分销赠送会员积分
                    third_tier_distribution($order['uid'],$order['final_amount'],$order['store_id'],$order['id'],0,$order['order_sn']);

                    //存在会员的openid就推送模板消息
                    if(!empty($member['openid'])){
                        //推送模板消息
                        $array = [
                            "type"   	  =>1,
                            "touser" 	  =>$member["openid"],
                            "template_id"=>config("mobanid.xiadan")["tempid"],
                            "url" 		  =>config("mobanid.xiadan")["url"],
                            "topcolor"  =>"#743A3A",
                            "data"   =>[
                                "first" 	    =>["value"=>"支付成功",        		"color"=>"#743A3A"],
                                "keyword1"		=>["value"=>$order['order_sn'], 		"color"=>"#743A3A"],
                                "keyword2"		=>["value"=>$order['final_amount'], 		"color"=>"#743A3A"],
                                "keyword3"		=>["value"=>"微信支付","color"=>"#743A3A"],
                                "remark"		=>["value"=>"感谢您的购买，请注意查收商品", 			"color"=>"#743A3A"],
                            ]
                        ];
                        $this->sendMessage($array);
                    }
                }
            }else{
                $this->error('支付失败',url('User/index'),1);
            }
        }
    }
    /**
     * @Author lignyun
     * @Desc    回调处理会员充值 -- 微信端
     *          会员三级分销积分、会员等级升级
     * 2018-03-21
     */
    public function wx_notifyrecharge(){
        $root = request()->domain();
        $pay = & load_wechat('Pay');
        // 获取支付通知
        $notifyInfo = $pay->getNotify();
        // 支付通知数据获取失败
        if($notifyInfo===FALSE){
            //处理失败接口
            db('user_wallet_log')->where('order_sn',$notifyInfo['out_trade_no'])->update(['charge_cn'=>$notifyInfo['return_msg'],'pay_status'=>-1]);
        }else{
            //支付通知数据获取成功
            if ($notifyInfo['result_code'] == 'SUCCESS' && $notifyInfo['return_code'] == 'SUCCESS') {
                $order = Db::name('user_wallet_log')->where("order_sn",$notifyInfo['out_trade_no'])->find();

                if($order['pay_status'] == 0){
                    $member = Db::name('user')->where('uid',$order['uid'])->find();     //会员信息
                    $cur_amount = $order['amount']+$member['user_money'];               //会员当前的金额

                    Db::name('user_wallet_log')->where('order_sn',$notifyInfo['out_trade_no'])->update(['pay_code'=>$notifyInfo['transaction_id'],'pay_status'=>1,'pay_time'=>time(),'cur_amount'=>$cur_amount]);     //更新支付记录

                    Db::name('user')->where('uid',$order['uid'])->setInc('user_money',$order['amount']);        //更新会员余额
                    Db::name('pay_log')->insert(['order_id'=>$order['id'],'order_sn'=>$order['order_sn'],'order_type'=>1,'uid'=>$order['uid'],'pay_type'=>$order['pay_type'],'pay_sign'=>2,'amount'=>$order['amount'],'addtime'=>time(),'remark'=>'会员充值，订单号'.$order['order_sn'].'，充值金额：'.$order['amount'],'store_id'=>$order['store_id']]);                  //新增支付记录

                    //会员充值三级分销变更记录
                    recharge_third_distribution($member['uid'],$order['amount']);

                    if(!empty($member['openid'])){
                        $root = request()->domain();
                        //推送模板消息
                        $array = [
                            "type"   	  =>1,
                            "touser" 	  =>$member["openid"],
                            "template_id"=>config("weixin_mu_msg.recharge_msg")["tempid"],
                            "url" 		  =>$root.'/index.php/index/user/recharge',
                            "topcolor"  =>"#743A3A",
                            "data"   =>[
                                "first" 	    =>["value"=>'充值成功提醒', "color"=>"#743A3A"],
                                "accountType" 	    =>["value"=>'充值时间', "color"=>"#743A3A"],
                                "account"		=>["value"=>date('Y-m-d H:i',time()), 		"color"=>"#743A3A"],
                                "amount"		=>["value"=>$order['total_amount'], 		"color"=>"#743A3A"],
                                "result"		=>["value"=>'充值成功',"color"=>"#743A3A"],
                                "remark"		=>["value"=>"您已成功充值，请注意卡内余额变动", 			"color"=>"#743A3A"],
                            ]
                        ];
                        $this->sendMessage($array);
                    }
                }
            }
        }
    }

    /**
     * @Author lignyun
     * @Desc    会员充值 -- 扫码充值回调
     */
    public function notifyweixinpay_code(){
        $root = request()->domain();
        $pay = & load_wechat('Pay');
        // 获取支付通知
        $notifyInfo = $pay->getNotify();
//        $sss = '{"appid":"wxca55ae67ce44cc82","bank_type":"CFT","cash_fee":"1","fee_type":"CNY","is_subscribe":"Y","mch_id":"1496012992","nonce_str":"7yp1oln3wy53q38icz6ifnmrjj7j48pr","openid":"ohW9z0y7Ia7iILgB9j2Y_otsIXb8","out_trade_no":"20180502200649844031000001","result_code":"SUCCESS","return_code":"SUCCESS","sign":"65EE7DC862991848C06038FD545CF543","time_end":"20180502200658","total_fee":"1","trade_type":"NATIVE","transaction_id":"4200000116201805021411925460"}';
//        $notifyInfo = json_decode($sss,true);

//        $resu = (array)simplexml_load_string(file_get_contents("php://input"), 'SimpleXMLElement', LIBXML_NOCDATA);
//$notifyInfo = file_get_contents("php://input");
//        file_put_contents('log.txt',json_encode($notifyInfo));
        // 支付通知数据获取失败
        if($notifyInfo===FALSE){
            //处理失败接口
            db('user_wallet_log')->where('order_sn',$notifyInfo['out_trade_no'])->update(['charge_cn'=>$notifyInfo['return_msg'],'pay_status'=>-1]);
        }else{
            //支付通知数据获取成功
            if ($notifyInfo['result_code'] == 'SUCCESS' && $notifyInfo['return_code'] == 'SUCCESS') {
                $order = Db::name('user_wallet_log')->where("order_sn",$notifyInfo['out_trade_no'])->find();
                if($order['pay_status'] == 0){
                    $member = Db::name('user')->where('uid',$order['uid'])->find();
                    $cur_amount = $order['amount']+$member['user_money'];
                    Db::name('user_wallet_log')->where('order_sn',$notifyInfo['out_trade_no'])->update(['pay_code'=>$notifyInfo['transaction_id'],'pay_status'=>1,'pay_time'=>time(),'cur_amount'=>$cur_amount]);     //更新支付记录
                    Db::name('user')->where('uid',$order['uid'])->setInc('user_money',$order['amount']);        //更新会员余额
                    Db::name('pay_log')->insert(['order_id'=>$order['id'],'order_sn'=>$order['order_sn'],'order_type'=>1,'uid'=>$order['uid'],'pay_type'=>$order['pay_type'],'pay_sign'=>2,'amount'=>$order['amount'],'addtime'=>time(),'remark'=>'会员充值，订单号'.$order['order_sn'].'，充值金额：'.$order['amount']]);                  //新增支付记录

                    //会员充值三级分销变更记录
                    recharge_third_distribution($member['uid'],$order['amount']);

                    if(!empty($member['openid'])){
                        $root = request()->domain();
                        //推送模板消息
                        $array = [
                            "type"   	  =>1,
                            "touser" 	  =>$member["openid"],
                            "template_id"=>config("weixin_mu_msg.recharge_msg")["tempid"],
                            "url" 		  =>$root.'/index.php/index/user/recharge',
                            "topcolor"  =>"#743A3A",
                            "data"   =>[
                                "first" 	    =>["value"=>'充值成功提醒', "color"=>"#743A3A"],
                                "accountType" 	    =>["value"=>'充值时间', "color"=>"#743A3A"],
                                "account"		=>["value"=>date('Y-m-d H:i',time()), 		"color"=>"#743A3A"],
                                "amount"		=>["value"=>$order['amount'], 		"color"=>"#743A3A"],
                                "result"		=>["value"=>'充值成功',"color"=>"#743A3A"],
                                "remark"		=>["value"=>"您已成功充值，请注意卡内余额变动", 			"color"=>"#743A3A"],
                            ]
                        ];

                        $this->sendMessage($array);
                    }
                }
            }
        }
    }

    /**
     * @Author  lingyun
     * @Desc    会员购买代金券回调业务处理
     */
    public function wx_buy_coupon_notify(){
        $pay = & load_wechat('Pay');
        // 获取支付通知
        $notifyInfo = $pay->getNotify();
//        $notifyInfo = '{"appid":"wx90f58e408924020c","bank_type":"CFT","cash_fee":"1","fee_type":"CNY","is_subscribe":"Y","mch_id":"1464515302","nonce_str":"8jyp82j2uwwmrjnldxojmg32nr8v9xjn","openid":"oXz3Mv_jneknLXQDAEQ7hC5uUoFI","out_trade_no":"20180112122717308352000080","result_code":"SUCCESS","return_code":"SUCCESS","sign":"4075C6D792DD588862F6630176CAE616","time_end":"20180103204530","total_fee":"1","trade_type":"NATIVE","transaction_id":"4200000036201801037576195587"}';
        // 支付通知数据获取失败
        if($notifyInfo===FALSE){
            // 接口失败的处理
            $this->error('支付失败',url('User/index'),1);
            //echo $pay->errMsg;
            //$json = json_encode($notifyInfo);
        }else{
            if ($notifyInfo['result_code'] == 'SUCCESS' && $notifyInfo['return_code'] == 'SUCCESS') {
                //会员的代金券列表
                $coupon = db('cash_coupon_list')->where('order_sn',$notifyInfo['out_trade_no'])->find();
                if($coupon['pay_status'] != 1){
                    //会员信息
                    $member = db('user')->where('uid',$coupon['uid'])->find();

                    $data_arr = [
                        'id'=>$coupon['id'],
                        'order_code'=>$notifyInfo['transaction_id'],
                        'pay_time'=>time(),
                        'pay_status'=>1,
                        'remark'=>'支付成功'
                    ];
                    db('cash_coupon_list')->data($data_arr)->update($data_arr);

//                    $data_arr1 = [
//                        'uid'=>$member['uid'],
//                        'store_id'=>$coupon['store_id'],
//                        'order_sn'=>$notifyInfo['out_trade_no'],
//                        'pay_time'=>time(),
//                        'pay_status'=>1,
//                        'pay_type'=>1,
//                        'amount'=>$coupon['price'],
//                        'cur_amount'=>$member['user_money'] - $coupon['price'],
//                        'sign'=>2,
//                        'charge_cn'=>'购买代金券',
//                        'addtime'=>time()
//                    ];
//                    db('user_wallet_log')->insert($data_arr1);

                    //会员积分
//                    third_tier_distribution($member['uid'],$coupon['price'],$coupon['store_id'],0,$money=0);          //去掉赠送积分
//                    $where_point_rule['id'] = ['eq',2];
//                    $point_rule = db('sys_point')->where($where_point_rule)->find();
//                    //变更的积分
//                    $point = ceil($coupon['price']/10);
//                    $data_arr2 = [
//                        'uid'=>$member['uid'],
//                        'store_id'=>session('store_id'),
//                        'uidtype'=>1,
//                        'signid'=>2,
//                        'type'=>1,
//                        'point'=>$point,
//                        'curpoint'=>$member['pay_points']+$point,
//                        'type_cn'=>'购买代金券赠送积分',
//                        'remark'=>'购买代金券赠送积分',
//                        'addtime'=>time(),
//                    ];
//                    db('user_point_log')->data($data_arr2)->insert();
//                    $cur_level_point = $member['level_point']+$point;
//                    $cur_pay_point = $member['pay_points']+$point;
//                    $point_rule = db('sys_level')->select();
//                    $level = userLevel($point_rule,$cur_level_point);
//                    $data_arr3 = [
//                        'uid'=>$member['uid'],
//                        'user_money'=>$member['user_money']-$coupon['price'],
//                        'level_point'=>$cur_level_point,
//                        'pay_points'=>$cur_pay_point,
//                    ];
//                    db('user')->data($data_arr3)->update();
                    //支付记录
                    $data_arr4 = [
                        'order_id'=>$coupon['id'],
                        'order_sn'=>$coupon['order_sn'],
                        'order_type'=>1,
                        'uid'=>$coupon['uid'],
                        'pay_type'=>$coupon['pay_type'],
                        'pay_sign'=>3,
                        'amount'=>$coupon['price'],
                        'addtime'=>time(),
                        'store_id'=>$coupon['store_id'],
                        'remark'=>'购买代金券，订单号'.$coupon['order_sn'].'，总价：'.$coupon['price'],
                    ];
                    db('pay_log')->data($data_arr4)->insert();

                    //购买的代金券
                    $cash_coupon = db('store_coupon')->where('id',$coupon['cash_coupon_id'])->find();
                    //创建会员代金券记录
                    $user_coupon_arr = [
                        'store_id'=>$coupon['store_id'],
                        'uid'=>$coupon['uid'],
                        'coupon_id'=>$coupon['cash_coupon_id'],
                        'type'=>2,
                        'cat_id'=>$coupon['cat_id'],
                        'condition'=>$cash_coupon['condition'],
                        'morethan'=>$cash_coupon['morethan'],
                        'reduce'=>$cash_coupon['reduce'],
                        'addtime'=>time(),
                        'price'=>$cash_coupon['price'],
                        'value'=>$cash_coupon['value'],
                        'use_start_time'=>$cash_coupon['use_start_time'],
                        'use_end_time'=>$cash_coupon['use_end_time'],
                        'is_used'=>0,
                        'status'=>1,
                    ];
                    //插入新增的数据
                    db('user_ycard')->data($user_coupon_arr)->insert();

                    //变更门店金额   --  记录数据
                    $store = db('store')->where('id',$coupon['store_id'])->find();
                    $store_credit_log = [
                        'store_id'=>$store['id'],
                        'order_id'=>$coupon['id'],
                        'type'=>1,
                        'credit'=>$cash_coupon['price'],
                        'cur_credit'=>$store['credit']+$cash_coupon['price'],
                        'remark'=>'销售代金券收入',
                        'addtime'=>time(),
                        'order_type'=>2,
                        'order_sn'=>$order['order_sn'],
                        'pay_type'=>2
                    ];
                    db('store_credit_log')->insert($store_credit_log);
                    $store_credit_arr = [
                        'total_amount'=>$store['total_amount']+$cash_coupon['price'],
                        'wx_money'=>$store['wx_money']+$cash_coupon['price']
                    ];
                    db('store')->where('id',$store['id'])->update($store_credit_arr);
                    //变更门店金额 - 更新记录

                    if(!empty($member['openid'])){
                        $root = request()->domain();
                        //推送模板消息
                        $array = [
                            "type"   	  =>1,
                            "touser" 	  =>$member["openid"],
                            "template_id"=>config("weixin_mu_msg.order_status")["tempid"],
                            "url" 		  =>$root.'/index.php/index/user/my_coupon',
                            "topcolor"  =>"#743A3A",
                            "data"   =>[
                                "first" 	    =>["value"=>'订单支付成功', "color"=>"#743A3A"],
                                "keyword1"		=>["value"=>$coupon['price'], 		"color"=>"#743A3A"],
                                "keyword2"		=>["value"=>date('Y-m-d H:i',time()), 		"color"=>"#743A3A"],
                                "keyword3"		=>["value"=>'支付成功',"color"=>"#743A3A"],
                                "remark"		=>["value"=>"订单支付成功，请到优惠券中心查看", 			"color"=>"#743A3A"],
                            ]
                        ];
                        $this->sendMessage($array);
                    }
                }
            }else{
                $this->error('支付失败',url('User/index'),1);
            }
        }
    }

    /**
     * @Author lignyun
     * @Desc    支付宝支付回调业务处理  --  下单回调业务处理
     */
    public function notifyalipay(){
        $request = input('param.');     //回调参数
        $request = json_decode(json_encode($request),true);     //解码
//        $request = '{"gmt_create":"2017-12-27 18:36:09","charset":"UTF-8","gmt_payment":"2017-12-27 18:36:15","notify_time":"2017-12-28 04:00:27","subject":"\u8ba2\u5355\u652f\u4ed8","sign":"bYV5QzJj76sMdMQJeJyY3p\/6cmPoZGkGMvyHSM010TPT4RNkoYI+onJNWfAKCJiDcITqGVm+ZYVKKa+0uogOfc3j5oo8XKKaLKLhHFi8pTYFarFZsWdZwq+DR+lpPBMayCC4pCmYyKFrJ3S4GqgFko\/MleOq2\/m28bSdm2AXNij+Cx5dEJ9nMQodCIrEqJUNgbQe9mGoE54CrXRd4xc+aQ1WQk02XHWWYE13BWIBuZtrQLRSyBdK5eatzPBs3BlI5yEEAnhqvoG01PxmY4NWgHjaUZWEwdWZ9ANUwn+KW1KQ7o2rou3uUiKr+TZzHFgK3m4dr74CpObsmuLOrqwJiQ==","buyer_id":"2088902557566724","invoice_amount":"0.01","version":"1.0","notify_id":"804d756db7b0244cc037d63ff75201elk2","fund_bill_list":"[{&quot;amount&quot;:&quot;0.01&quot;,&quot;fundChannel&quot;:&quot;ALIPAYACCOUNT&quot;}]","notify_type":"trade_status_sync","out_trade_no":"201712271514370960963561","total_amount":"0.01","trade_status":"TRADE_SUCCESS","trade_no":"2017122721001004720205067586","auth_app_id":"2017112500161947","receipt_amount":"0.01","point_amount":"0.00","app_id":"2017112500161947","buyer_pay_amount":"0.01","sign_type":"RSA2","seller_id":"2088521346175024"}';
        $result = Query::exec($request['out_trade_no']);        //主动发起查询结果请求
        if($result['code'] == '10000'){     //调用接口成功
            if(isset($result['trade_status']) && $result['trade_status'] == 'TRADE_SUCCESS'){  //支付成功
                //查询订单信息
                $order = Db::name('order')->where('order_sn',$result['out_trade_no'])->find();
                $member = Db::name('user')->where('uid',$order['uid'])->find();     //会员信息
                if($order['pay_status'] == 0){
                    //更新订单状态
                    Db::name('order')->where('order_sn',$result['out_trade_no'])->update(['pay_code'=>$result['trade_no'],'pay_status'=>1,'pay_time'=>strtotime($result['send_pay_date']),'order_status'=>1,'remark'=>'已支付']);
                    //支付记录
//                    Db::name('pay_log')->insert(['order_id'=>$order['id'],'order_sn'=>$result['out_trade_no'],'order_type'=>1,'uid'=>$order['uid'],'pay_type'=>1,'pay_sign'=>1,'amount'=>$result['total_amount'],'addtime'=>time(),'remark'=>'支付订单']);
                    //订单动作
                    Db::name('order_action')->insert(['uid'=>$order['uid'],'order_id'=>$order['id'],'action_user'=>0,'order_status'=>1,'pay_status'=>1,'status_desc'=>'已支付，待发货','storeid'=>$order['store_id'],'addtime'=>time()]);

                    //订单详情
                    $order_detail = db('order_details')->where('order_id',$order['id'])->field('id,uid,goods_num,order_id,spec_id,spec_detail,store_goods_stock_id')->select();

                    $ids = implode(',',array_column($order_detail, 'id'));
//                    $store_goods_stock_id = implode(',',array_column($order_detail, 'store_goods_stock_id'));

                    //更新订单详情的支付状态
                    db('order_details')->where('id','in',$ids)->update(['status'=>1]);
                    foreach($order_detail as $k => $v){
                        //更新门店库存
//                        db('store_goods_stock')->where('id',$v['store_goods_stock_id'])->setDec('stock',$v['goods_num']);
                        $stock = db('store_goods_stock')->where('id',$v['store_goods_stock_id'])->find();
                        $cur_stock = $stock['stock'] - $v['goods_num'];
                        //更新门店库存
                        db('store_goods_stock')->where('id',$v['store_goods_stock_id'])->update(['stock'=>$cur_stock]);
                        $arr = [
                            'goods_id'=>$v['goods_id'],
                            'goods_spec_id'=>$stock['goods_spec_id'],
                            'title'=>$v['spec_detail'],
                            'order_id'=>$order['id'],
                            'store_id'=>$order['store_id'],
                            'types'=>2,
                            'ruku_num'=>0,
                            'tuihuo_num'=>0,
                            'chuku_num'=>$v['goods_num'],
                            'sunhao_num'=>0,
                            'remark'=>'售卖'.$v['goods_num'],
                            'cur_stock'=>$cur_stock,
                            'addtime'=>time(),
                            'order_sn'=>$order['order_sn'],
                        ];
                        db('store_goods_log')->insert($arr);
                    }

                    //更新优惠券的使用情况
                    db('user_ycard')->where(['uid'=>$order['uid'],'id'=>$order['coupon_id']])->update(['order_id'=>$order['id'],'used_time'=>time(),'is_used'=>1]);
                    //更新代金券的使用情况
                    db('user_ycard')->where(['uid'=>$order['uid'],'id'=>$order['cash_coupon_id']])->update(['order_id'=>$order['id'],'used_time'=>time(),'is_used'=>1]);

                    $pay_log_arr = [
                        'order_id'=>$order['id'],
                        'order_sn'=>$order['order_sn'],
                        'order_type'=>1,
                        'uid'=>$order['uid'],
                        'pay_type'=>$order['pay_type'],
                        'pay_sign'=>1,
                        'amount'=>$order['final_amount'],
                        'remark'=>'线上购买商品，订单号'.$order['order_sn'].'，总价：'.$order['final_amount'],
                        'addtime'=>time(),
                        'store_id'=>$order['store_id']      //门店id
                    ];
                    db('pay_log')->insert($pay_log_arr);            //新增支付记录
                    //增加门店线上微信收入

                    $update_store_credit_data = [
                        'total_amount'=>$store['total_amount']+$order['final_amount'],
                        'al_money'=>$store['al_money']+$order['final_amount']
                    ];
                    //增加门店线上微信收入
                    db('store')->where('id',$order['store_id'])->update($update_store_credit_data);

                    $store_credit_log = [
                        'store_id' => $order['store_id'],
                        'order_id' => $order['id'],
                        'type' => 1,
                        'credit' => $order['final_amount'],
                        'cur_credit' => $store['total_amount'] + $order['final_amount'],
                        'remark' => '销售商品收入',
                        'addtime' => time(),
                        'order_type' => 1,
                        'order_sn' => $order['order_sn'],
                        'pay_type' => 1
                    ];

                    db('store_credit_log')->insert($store_credit_log);

                    db('store')->where('id',$order['store_id'])->setInc('al_money',$order['final_amount']);

                    third_tier_distribution($order['uid'],$order['final_amount'],$order['store_id'],$order['id'],$money=0,$order['order_sn']);

                    //存在会员的openid就推送模板消息
                    if(!empty($member['openid'])){
                        file_put_contents('log.txt',$member['openid']);
                        //推送模板消息
                        $array = [
                            "type"   	  =>1,
                            "touser" 	  =>$member["openid"],
                            "template_id"=>config("mobanid.xiadan")["tempid"],
                            "url" 		  =>config("mobanid.xiadan")["url"],
                            "topcolor"  =>"#743A3A",
                            "data"   =>[
                                "first" 	    =>["value"=>"支付成功",        		"color"=>"#743A3A"],
                                "keyword1"		=>["value"=>$order['order_sn'], 		"color"=>"#743A3A"],
                                "keyword2"		=>["value"=>$order["final_amount"], 		"color"=>"#743A3A"],
                                "keyword3"		=>["value"=>'支付宝支付',"color"=>"#743A3A"],
                                "remark"		=>["value"=>"感谢您的购买，请注意查收商品", 			"color"=>"#743A3A"],
                            ]
                        ];
                        $this->sendMessage($array);
                    }
                }
            }else{
                Db::name('order')->where('order_sn',$result['out_trade_no'])->update(['remark'=>$result['sub_msg']]);
            }
        }
    }

    /**
     * @Author lignyun
     * @Desc    会员充值 -- 支付宝回调
     * 2018-03-21
     */
    public function notifyalirecharge(){
        $root = request()->domain();
        $request = input('param.');     //回调参数
        $request = json_decode(json_encode($request),true);     //解码
        $result = Query::exec($request['out_trade_no']);        //主动发起查询结果请求
//        file_put_contents('log.txt',json_encode($result));
//        $s = '{"code":"10000","msg":"Success","buyer_logon_id":"tia***@163.com","buyer_pay_amount":"0.00","buyer_user_id":"2088902557566724","invoice_amount":"0.00","out_trade_no":"20180206162033846359000080","point_amount":"0.00","receipt_amount":"0.00","send_pay_date":"2018-02-06 16:20:50","total_amount":"0.01","trade_no":"2018020621001004720202446661","trade_status":"TRADE_SUCCESS"}';
//        $result = json_decode($s,true);
        if($result['code'] == '10000'){     //调用接口成功
            if(isset($result['trade_status']) && $result['trade_status'] == 'TRADE_SUCCESS'){  //支付成功
                //查询订单信息
                $order = Db::name('user_wallet_log')->where('order_sn',$result['out_trade_no'])->find();
                if($order['pay_status'] == 0){
                    //会员信息
                    $member = Db::name('user')->where('uid',$order['uid'])->find();
                    $cur_amount = $member['user_money']+$result['total_amount'];        //会员当前余额

                    //变更会员余额
                    Db::name('user')->where('uid',$order['uid'])->setInc('user_money',$result['total_amount']);
                    //更新订单状态
                    Db::name('user_wallet_log')->where('order_sn',$result['out_trade_no'])->update(['pay_code'=>$result['trade_no'],'pay_time'=>strtotime($result['send_pay_date']),'pay_status'=>1,'pay_type'=>1,'amount'=>$result['total_amount'],'cur_amount'=>$cur_amount,'sign'=>2,'chargetype'=>2,'charge_cn'=>'余额充值']);
                    //记录支付日志
                    Db::name('pay_log')->insert(['order_id'=>$order['id'],'order_sn'=>$result['out_trade_no'],'order_type'=>1,'uid'=>$order['uid'],'pay_type'=>1,'pay_sign'=>2,'amount'=>$result['total_amount'],'addtime'=>time(),'remark'=>'会员充值，订单号'.$order['order_out_trade_no'].'，充值金额：'.$order['total_amount'],'store_id'=>$order['store_id']]);

                    //会员充值三级分销变更记录
                    recharge_third_distribution($member['uid'],$result['total_amount']);

                    if(!empty($member['openid'])){
                        $root = request()->domain();
                        //推送模板消息
                        $array = [
                            "type"   	  =>1,
                            "touser" 	  =>$member["openid"],
                            "template_id"=>config("weixin_mu_msg.recharge_msg")["tempid"],
                            "url" 		  =>$root.'/index.php/index/user/recharge',
                            "topcolor"  =>"#743A3A",
                            "data"   =>[
                                "first" 	    =>["value"=>'充值成功提醒', "color"=>"#743A3A"],
                                "accountType" 	    =>["value"=>'充值时间', "color"=>"#743A3A"],
                                "account"		=>["value"=>date('Y-m-d H:i',time()), 		"color"=>"#743A3A"],
                                "amount"		=>["value"=>$result['total_amount'], 		"color"=>"#743A3A"],
                                "result"		=>["value"=>'充值成功',"color"=>"#743A3A"],
                                "remark"		=>["value"=>"您已成功充值，请注意卡内余额变动", 			"color"=>"#743A3A"],
                            ]
                        ];
                        $this->sendMessage($array);
                    }
                }
            }else{
                Db::name('user_wallet_log')->where('order_sn',$result['out_trade_no'])->update(['remark'=>$result['sub_msg'],'pay_status'=>-1]);
            }
        }
    }

    /**
     * @Author  lignyun
     * @Desc    支付宝购买代金券回调url
     */
    public function ali_coupon_notify(){
        $request = input('param.');     //回调参数
        $request = json_decode(json_encode($request),true);     //解码
        $result = Query::exec($request['out_trade_no']);        //主动发起查询结果请求
//        file_put_contents('log.txt',json_encode($result));

//        $s = '{"code":"10000","msg":"Success","buyer_logon_id":"tia***@163.com","buyer_pay_amount":"0.00","buyer_user_id":"2088902557566724","invoice_amount":"0.00","out_trade_no":"20180207144654147714000080","point_amount":"0.00","receipt_amount":"0.00","send_pay_date":"2018-02-07 14:47:12","total_amount":"0.01","trade_no":"2018020721001004720205333272","trade_status":"TRADE_SUCCESS"}';
//        $result = json_decode($s,true);
//        $request = $result;

        if($result['code'] == '10000'){     //调用接口成功
            if(isset($result['trade_status']) && $result['trade_status'] == 'TRADE_SUCCESS'){  //支付成功
                //会员的代金券列表
                $coupon = db('cash_coupon_list')->where('order_sn',$request['out_trade_no'])->find();
                if($coupon['pay_status'] != 1){
                    //会员信息
                    $member = db('user')->where('uid',$coupon['uid'])->find();

                    $data_arr = [
                        'id'=>$coupon['id'],
                        'order_code'=>$result['trade_no'],
                        'pay_time'=>strtotime($result['send_pay_date']),
                        'pay_status'=>1,
                        'remark'=>'支付成功'
                    ];
                    db('cash_coupon_list')->data($data_arr)->update($data_arr);

//                    third_tier_distribution($member['uid'],$coupon['price'],$coupon['store_id'],0,$money=0);        //取消赠送积分

//                    $data_arr1 = [
//                        'uid'=>$member['uid'],
//                        'store_id'=>$coupon['store_id'],
//                        'order_sn'=>$request['out_trade_no'],
//                        'pay_time'=>time(),
//                        'pay_status'=>1,
//                        'pay_type'=>1,
//                        'amount'=>$coupon['price'],
//                        'cur_amount'=>$member['user_money'] - $coupon['price'],
//                        'sign'=>2,
//                        'charge_cn'=>'购买代金券',
//                        'addtime'=>time()
//                    ];
//                    db('user_wallet_log')->insert($data_arr1);
//                    $where_point_rule['id'] = ['eq',2];
//                    $point_rule = db('sys_point')->where($where_point_rule)->find();
//                    //变更的积分
//                    $point = ceil($coupon['price']/10)*$point_rule['point'];
//                    $data_arr2 = [
//                        'uid'=>$member['uid'],
//                        'store_id'=>session('store_id'),
//                        'uidtype'=>1,
//                        'signid'=>2,
//                        'type'=>1,
//                        'point'=>$point,
//                        'curpoint'=>$member['pay_points']+$point,
//                        'type_cn'=>'购买代金券赠送积分',
//                        'remark'=>'购买代金券赠送积分',
//                        'addtime'=>time(),
//                    ];
//                    db('user_point_log')->data($data_arr2)->insert();
//                    $cur_level_point = $member['level_point']+$point;
//                    $cur_pay_point = $member['pay_points']+$point;
//                    $point_rule = db('sys_level')->select();
//                    $level = userLevel($point_rule,$cur_level_point);
//                    $data_arr3 = [
//                        'uid'=>$member['uid'],
//                        'user_money'=>$member['user_money']-$coupon['price'],
//                        'level_point'=>$cur_level_point,
//                        'pay_points'=>$cur_pay_point,
//                        'level_id'=>$level
//                    ];
//                    db('user')->data($data_arr3)->update();
                    //支付记录
                    $data_arr4 = [
                        'order_id'=>$coupon['id'],
                        'order_sn'=>$coupon['order_sn'],
                        'order_type'=>1,
                        'uid'=>$coupon['uid'],
                        'pay_type'=>$coupon['pay_type'],
                        'pay_sign'=>3,
                        'amount'=>$coupon['price'],
                        'addtime'=>time(),
                        'store_id'=>$coupon['store_id'],
                        'remark'=>'购买代金券，订单号'.$coupon['order_sn'].'，总价：'.$coupon['price'],
                    ];
                    db('pay_log')->data($data_arr4)->insert();      //支付记录

                    //购买的代金券
                    $cash_coupon = db('store_coupon')->where('id',$coupon['cash_coupon_id'])->find();
                    //创建会员代金券记录
                    $user_coupon_arr = [
                        'store_id'=>$coupon['store_id'],
                        'uid'=>$coupon['uid'],
                        'coupon_id'=>$coupon['cash_coupon_id'],
                        'type'=>2,
                        'cat_id'=>$coupon['cat_id'],
                        'condition'=>$cash_coupon['condition'],
                        'morethan'=>$cash_coupon['morethan'],
                        'reduce'=>$cash_coupon['reduce'],
                        'addtime'=>time(),
                        'price'=>$cash_coupon['price'],
                        'value'=>$cash_coupon['value'],
                        'use_start_time'=>$cash_coupon['use_start_time'],
                        'use_end_time'=>$cash_coupon['use_end_time'],
                        'is_used'=>0,
                        'status'=>1,
                    ];


                    //变更门店金额   --  记录数据

                    //插入新增的数据
                    db('user_ycard')->data($user_coupon_arr)->insert();

                    //变更门店金额   --  记录数据
                    $store = db('store')->where('id',$coupon['store_id'])->find();
                    $store_credit_log = [
                        'store_id'=>$store['id'],
                        'order_id'=>$coupon['id'],
                        'type'=>1,
                        'credit'=>$cash_coupon['price'],
                        'cur_credit'=>$store['credit']+$cash_coupon['price'],
                        'remark'=>'销售代金券收入',
                        'addtime'=>time(),
                        'order_type'=>2,
                        'order_sn'=>$order['order_sn'],
                        'pay_type'=>1
                    ];
                    db('store_credit_log')->insert($store_credit_log);
                    $store_credit_arr = [
                        'total_amount'=>$store['total_amount']+$cash_coupon['price'],
                        'al_money'=>$store['al_money']+$cash_coupon['price']
                    ];
                    db('store')->where('id',$store['id'])->update($store_credit_arr);
                    //变更门店金额 - 更新记录

                    if(!empty($member['openid'])){
                        $root = request()->domain();
                        //推送模板消息
                        $array = [
                            "type"   	  =>1,
                            "touser" 	  =>$member["openid"],
                            "template_id"=>config("weixin_mu_msg.order_status")["tempid"],
                            "url" 		  =>$root.'/index.php/index/user/my_coupon',
                            "topcolor"  =>"#743A3A",
                            "data"   =>[
                                "first" 	    =>["value"=>'订单支付成功', "color"=>"#743A3A"],
                                "keyword1"		=>["value"=>$coupon['price'], 		"color"=>"#743A3A"],
                                "keyword2"		=>["value"=>date('Y-m-d H:i',time()), 		"color"=>"#743A3A"],
                                "keyword3"		=>["value"=>'支付成功',"color"=>"#743A3A"],
                                "remark"		=>["value"=>"订单支付成功，请到优惠券中心查看", 			"color"=>"#743A3A"],
                            ]
                        ];
                        $this->sendMessage($array);
                    }
                }
            }
        }else{
            db('cash_coupon_list')->where('order_sn',$result['out_trade_no'])->update(['remark'=>$result['sub_msg']]);
        }
    }

    /**
     * @Author lignyun
     * @Desc    推送模板消息
     */
    private function sendMessage($array){
        $wein = new WeixinService();
        $rest  = $wein->sendmsg($array);
    }

    /**
     * @Author  lignyun
     * @Desc    模板消息推送
     */
    public function tuisong(){
//        $member['openid'] = "oXz3Mv_jneknLXQDAEQ7hC5uUoFI";
        $member = Db::name('user')->where("openid",'oXz3Mv_jneknLXQDAEQ7hC5uUoFI')->find();
        $order = Db::name('user_wallet_log')->where('order_sn','20180103202932681317000061')->find();
        $cur_amount = $member['user_money']+$order['amount'];
        $array = [
            "type"   	  =>1,
            "touser" 	  =>$member["openid"],
            "template_id"=>config("mobanid.xiadan")["tempid"],
            "url" 		  =>config("mobanid.xiadan")["url"],
            "topcolor"  =>"#743A3A",
            "data"   =>[
                "first" 	    =>["value"=>'充值成功', "color"=>"#743A3A"],
                "keyword1"		=>["value"=>$order['amount'], 		"color"=>"#743A3A"],
                "keyword2"		=>["value"=>date('Y-m-d H:i',time()), 		"color"=>"#743A3A"],
                "keyword3"		=>["value"=>$cur_amount,"color"=>"#743A3A"],
                "remark"		=>["value"=>"您已成功充值，请注意卡内余额变更", 			"color"=>"#743A3A"],
            ]
        ];
        $this->sendMessage($array);

    }



}